//
//  YYViewController.m
//  Courses
//
//  Created by YiXuePxh on 15/4/15.
//  Copyright (c) 2015年 boyibang. All rights reserved.
//

#import "YYViewController.h"

#include "../depends/include/sdkhelpers.h"

#include <string>

#include <sys/time.h>

#import "../depends/include/VideoOutput.h"
#import "../depends/include/VideoView.h"

#import "WTFColors.h"

#define YY 4923  //益学yy频道
@interface YYViewController ()
@property(nonatomic,strong)UIView* videoViewV;
@property(nonatomic,assign)int num;
@property(nonatomic,strong)UIView* status;
@end

@implementation YYViewController{
    VideoOutput* m_videoOutput;
    VideoView* m_videoView;
}


 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
     if (self) {
            // Custom initialization.
         //隐藏  tabbar
            self.hidesBottomBarWhenPushed = YES;
         //view旋转
         [self.view setTransform:CGAffineTransformMakeRotation(M_PI/2)];
     }
    return self;
 }

-(UIStatusBarStyle) preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
-(BOOL)prefersStatusBarHidden{
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    //获取屏幕尺寸
    CGRect screenRect= [UIScreen mainScreen].applicationFrame;
    CGRect statusRect = [[UIApplication sharedApplication] statusBarFrame];
    _num = 0;
    _status = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenRect.size.height + statusRect.size.height, 20)];
    _status.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.7];
    UIButton* btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 20)];
    [btn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [_status addSubview:btn];
    
    //创建点击手势
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
    //阻止屏幕变暗进入休眠状态
    [UIApplication sharedApplication].idleTimerDisabled =YES;
    // Do any additional setup after loading the view.
    CGRect showRect = CGRectMake(0, 0, screenRect.size.height + statusRect.size.height, screenRect.size.width);
    _videoViewV = [[UIView alloc] initWithFrame:showRect];
//    _videoViewV.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_videoViewV];
    // 添加回掉事件
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(handleGuestLoginAck:) name:kGuestLoginNotification object:nil];
    [center addObserver:self selector:@selector(handleLoginAck:) name:kLoginNotification object:nil];
    [center addObserver:self selector:@selector(handleLoginBrokenAck:) name:KLoginBrokeNotification object:nil];
    [center addObserver:self selector:@selector(handleKickOffAck:) name:kKickOffNotification object:nil];
    [center addObserver:self selector:@selector(handleImageCodeVerifyAck:) name:kImageCodeVerifyNotification object:nil];
    [center addObserver:self selector:@selector(handleLinkStatusChangedAck:) name:kLinkStateChangedNotification object:nil];
    [center addObserver:self selector:@selector(handleJoinChannelAck:) name:kChannelJoinNotification object:nil];
    [center addObserver:self selector:@selector(handleKickOffChannelAck:) name:kChannelKickOffNotification object:nil];
    [center addObserver:self selector:@selector(handleChannelTextArrived:) name:kChannelTextArrivedNotification object:nil];
    [center addObserver:self selector:@selector(handleSendTextFailedAck:) name:kTextChatServiceResultNotification object:nil];
    [center addObserver:self selector:@selector(handleVideoStreamsChanged:) name:kChannelVideoStreamChangedNotification object:nil];
    [center addObserver:self selector:@selector(handleVideoRender:) name:kChannelVideoRenderNotification object:nil];
    
    //匿名登陆
    [self onGuestLoginClicked];
    //进入 频道
    [self onJoinChannelClicked];
    
    
    [self.view addSubview:_status];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //隐藏navigationController
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    //隐藏状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //显示状态栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    //显示navigationController
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    //隐藏 Tabbar
//    [self.tabBarController.tabBar setHidden:YES];
//    [self.tabBarController setHidesBottomBarWhenPushed:YES];
}

//点击事件 回调方法
-(void)tapAction{
    NSLog(@"..................%d",_num);
    if (_num == 0 && _status.hidden == NO) {
         _num ++;
        _status.hidden = YES;
    }else{
        _num = 0;
        _status.hidden = NO;
    }
    
}

//返回前一页
- (void)clickBack {
    //状态栏旋转
//    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
    [self.navigationController popToRootViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onGuestLoginClicked{
    // 匿名登录服务器
    [[AppHelper sharedObject].loginHelper guestLogin];
    NSLog(@"匿名登录服务器");
}


//- (IBAction)onLoginClicked:(id)sender {
//    [_userNameTf resignFirstResponder];
//    [_passwrodTf resignFirstResponder];
//    
//    NSString *userName = _userNameTf.text;
//    NSString *password = _passwrodTf.text;
//    if (userName == NULL || userName.length <= 0) {
//        _messageTipTv.text = @"用户登录时，用户名不能为空";
//        return;
//    }
//    
//    if (password == NULL || password.length <= 0) {
//        _messageTipTv.text = @"用户登录时，密码不能为空";
//        return;
//    }
//    
//    //用户登录
//    [[AppHelper sharedObject].loginHelper loginWithName:userName password:password loginOption:[SdkLoginOption defaultOption]];
//}

- (void)onLogoutClicked{
    // 退出用户登录
    [[AppHelper sharedObject].loginHelper logout];
}

- (void)onJoinChannelClicked{
//    [_channelIdTf resignFirstResponder];
    
    // 进入频道
    [[AppHelper sharedObject].channelHelper joinChannel:(uint32_t)YY subSid:0 checkOtherClient:NO kickToken:@""];
    
    if (m_videoOutput == nil) {
        m_videoOutput = [[VideoOutput alloc] init];
    }
    
    // 添加视频显示VIEW
    if (m_videoView == nil) {
        m_videoView = [[VideoView alloc] initWithFrame:_videoViewV.bounds];
        [m_videoView setBackgroundColor:[UIColor blueColor]];
        [m_videoOutput addVideoView:m_videoView];
        [_videoViewV addSubview:m_videoView];
    }
    [m_videoOutput start];
}


- (void)onLeaveChannelClicked{
    // 退出频道
    ChannelHelper *channelHelper = [AppHelper sharedObject].channelHelper;
    [channelHelper quitChannel];
    
    // 删除视频view
    [m_videoOutput stop];
    [m_videoOutput removeVideoView:m_videoView];
    [m_videoView removeFromSuperview];
    m_videoView = nil;
    m_videoOutput = nil;
}


//- (IBAction)onSendTextClicked:(id)sender {
//    [_sendTextTf resignFirstResponder];
//    
//    // 发送频道聊天文字
//    ChannelHelper* channelHelper = [[AppHelper sharedObject] channelHelper];
//    int waitingSeconds = 0;
//    [channelHelper sendText:channelHelper.subSid text:_sendTextTf.text waitingSeconds:&waitingSeconds];
//}



// 匿名登录结果回掉
- (void)handleGuestLoginAck:(NSNotification *)notification {
    NSLog(@"匿名登录成功");
}

// 用户登录结果回掉
- (void)handleLoginAck:(NSNotification *)notification {
    NSNumber *result = [notification userInfo][kLoginResultUserInfoKey];
//    _messageTipTv.text = [NSString stringWithFormat:@"用户登录结果：%@" ,result];
    NSLog(@"用户登录结果：%@" ,result);
}

// 登录掉线回掉
- (void)handleLoginBrokenAck:(NSNotification *)notification {
    
}

// 帐号被踢掉或者被封通知
- (void)handleKickOffAck:(NSNotification *)notification {
    
}

// 登录中需要验证码通知
- (void)handleImageCodeVerifyAck:(NSNotification *)notification {
    // 收到后显示图形验证码，回复接口为：
    // 1 填写验证码 [[AppHelper sharedObject].loginHelper answerImageCode
    // 2 刷新验证码 [[AppHelper sharedObject].loginHelper refreshPicCode
}

// 网络状态变化通知
- (void)handleLinkStatusChangedAck:(NSNotification *)notification {
    
}


// 进频道结果回掉
- (void)handleJoinChannelAck:(NSNotification *)notification {
    NSNumber *result = [notification userInfo][kChannelResultKey];
//    _messageTipTv.text = [NSString stringWithFormat:@"进频道结果：%@" ,result];
    NSLog(@"进频道结果：%@" ,result);
}

// 被踢出频道回掉
- (void)handleKickOffChannelAck:(NSNotification *)notification {
    
}

// 公频聊天信息到达通知
- (void)handleChannelTextArrived:(NSNotification *)notification {
    NSDictionary * userInfo = notification.userInfo;
    NSString * channelText = [NSString stringWithFormat:@"%@  %@\n%@",
                              userInfo[kChannelNickKey], userInfo[kChannelTimestampKey],
                              userInfo[kChannelTextKey]];
//    _messageTipTv.text = channelText;
}

// 发送公频信息失败时调用
- (void)handleSendTextFailedAck:(NSNotification *)notification {
    NSNumber *res = [[notification userInfo] objectForKey:kTextChatServiceReslutKey];
//    _messageTipTv.text = [NSString stringWithFormat:@"发送聊天信息失败：%@" ,res];
}

// 视频流发生变化时调用，进频道也会通知一次
- (void)handleVideoStreamsChanged:(NSNotification *)notification {
    ChannelHelper* channelHelper = [AppHelper sharedObject].channelHelper;
    NSArray* streams = channelHelper.videoStreams;
    if (streams.count > 0) {
        SdkVideoStream* vs = [streams objectAtIndex:0];
        [m_videoView connectToVideoInfo:vs.streamId userGroupId:vs.userGroupId];
        [channelHelper openVideo:vs];
    }
}

- (void)handleVideoRender:(NSNotification *)notification {
    SdkMediaVideoParam *param = [[notification userInfo] objectForKey:kChannelMediaVideoParamKey];
    [m_videoOutput render:param.data];
}

- (void)dealloc {
    //退出用户登陆
    [self onLogoutClicked];
    [self onLeaveChannelClicked];
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    // 删除回掉事件
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
